package com.skt.TFriend.widget;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Random;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;

import com.skt.TFriend.R;
import com.skt.TFriend.Data.Weather_Data;
import com.skt.TFriend.activities.Traffic_Info;
import com.skt.TFriend.activities.Weather_Info;

public class T_Friend_Widget extends AppWidgetProvider{

	private static final String TAG = "T_Friend_Widget";
	private static AlarmManager mManager; 
	private static String current_scr = "";

	public static ComponentName mService = null;
	public static boolean endServiceFlag = false;
	public static int curCount = 0;
	public static int maxCount = 0;
	public static String category = com.skt.TFriend.util.Constants.NEWS_CATEGORY;
	public static final String NEWS = com.skt.TFriend.util.Constants.NEWS_CATEGORY;;
	public static final String WEATHER = com.skt.TFriend.util.Constants.WEATHER_CATEGORY;;
	public static Random  random = new Random();
	public static String[] weather_data ={"비","눈","맑음","태풍","소나기","흐림"};
	public static String[] traffic_data ={"교통정보1","교통정보2","교통정보3","교통정보4","교통정보5","교통정보6"};
	public static String[] test_data ={"11111111","222222222","33333333","444444","555555","666666"};
	public static String[]  new_title ={"'군통령' 시크릿 전효성, '자극적 터치'","日 '센카쿠 1m동 양보 안겠다' 선전포고","朴·文·安, 치열한 공방에도 지지율은..."};
	public static Integer[] new_image = {R.drawable.new01,R.drawable.new02,R.drawable.new03};
	public static String[] new_url   ={"http://osen.mt.co.kr/article/G1109482568","http://news.hankyung.com/201210/2012101673828.html?ch=news","http://news.chosun.com/site/data/html_dir/2012/10/17/2012101700217.html"};
	public static String[] show_data;
	
	@Override
	public void onDeleted(Context context, int[] appWidgetIds) {
		// TODO Auto-generated method stub
		super.onDeleted(context, appWidgetIds);
		current_scr="";
		endServiceFlag = true;		
	}

	@Override
	public void onDisabled(Context context) {
		// TODO Auto-generated method stub
		super.onDisabled(context);
	}
	
	//처음 한번만 호출되면 끝..
	@Override
	public void onEnabled(Context context) {
		// TODO Auto-generated method stub
		super.onEnabled(context);
		endServiceFlag = false;
//		show_data = weather_data;
//		
//		Intent intent2 = new Intent();
//		intent2.setAction(com.skt.TFriend.util.Constants.WEATHER_WIDGET_UPDATE_NAME);
//		Weather_Data wdata = new Weather_Data();
//		Weather_Data wdata1 = new Weather_Data();
//		wdata.setTemp("19");
//		wdata.setWfKor("테스트온도!");
//		wdata1.setTemp("20");
//		wdata1.setWfKor("테스트!!!!!!");
//		ArrayList<Weather_Data>  wd1 = new ArrayList<Weather_Data>();
//		wd1.add(wdata);
//		wd1.add(wdata1);
//		//wd1.set(0, wdata);
//		//wd1.set(1, wdata1);
//		intent2.putParcelableArrayListExtra("weatherArrayList", wd1);
//		//IntegerArrayListExtra("weatherArrayList", wd1);
//		
//		
//		mManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
//		
//		Log.i(TAG, "1111111111111");
//		Calendar calendar = Calendar.getInstance();
//		Log.i(TAG, "2222222222222");
//		PendingIntent pInt = PendingIntent.getBroadcast(context, 0, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
//		Log.i(TAG, "3333333333333");
//		long triggerTime = SystemClock.elapsedRealtime() + 1000*60;
//		Log.i(TAG, "44444444triggerTime=>"+triggerTime);
//		Log.i(TAG, "현재시간1=>"+SystemClock.elapsedRealtime()); //sleep포함하여 부팅후 시간(밀리초)
//		Log.i(TAG, "현재시간2=>"+System.currentTimeMillis());
//		mManager.set(AlarmManager.ELAPSED_REALTIME ,  triggerTime, pInt);
		// alarm 등록여부 체크(처음 설치시 등록하기위해)
		
//		Calendar calendar = Calendar.getInstance();
//		
//		Intent intent = new Intent();
//		intent.setAction("COM.SKT.TFRIEND.WEATHER_ALARM");
//		 
//		PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//		mManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
//		mManager.setRepeating(AlarmManager.RTC, calendar.getTimeInMillis(), 60000, pIntent); 
		// 알람속성, 알람실행시간,
		//매시 30분 알람이 있는지 체크 없으면 알람등록.....
		
		//테스트용
		Intent intent = new Intent();
		intent.setAction(com.skt.TFriend.util.Constants.WEATHER_ALARM_ACTION_NAME);
		
		PendingIntent pIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		mManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
		mManager.set(AlarmManager.ELAPSED_REALTIME ,  30000, pIntent);
	}
	
	// 위젯에서 사용자 event가 발생 처리
	// 위젯에 어떤 정보가 보여야할지 처리 
	@Override
	public void onReceive(Context context, Intent intent) {
		Log.i(TAG, "onReceive : onReceive");
		if(intent.getAction()==null){
			Log.i(TAG, "onReceive : intent.getAction()==null");
		}else{
			Log.i(TAG, "onReceive: action="+intent.getAction());
			super.onReceive(context, intent);
			
			if(intent.getAction().equals("COM.SKT.TFRIEND.UPBUTTON.CLICKED")){
				current_scr ="UPBUTTON.CLICKED";
			}else if(intent.getAction().equals("COM.SKT.TFRIEND.DOWNBUTTON.CLICKED")){
				current_scr ="DOWNBUTTON.CLICKED";
			}else if(intent.getAction().equals(com.skt.TFriend.util.Constants.WEATHER_ALARM_ACTION_NAME)){
				Log.i(TAG, "onReceive: action="+intent.getAction());
				show_data = traffic_data;
			}else if(intent.getAction().equals(com.skt.TFriend.util.Constants.WEATHER_WIDGET_UPDATE_NAME)){
				
				//category = WEATHER;USER_PREFERENCES
				SharedPreferences pref = context.getSharedPreferences(com.skt.TFriend.util.Constants.USER_PREFERENCES, Context.MODE_PRIVATE);
				long alarm_duration_time = pref.getLong(com.skt.TFriend.util.Constants.ALARM_DURATION_TIME, 300000);
		
				Log.i(TAG, "################COM.SKT.TFRIEND.WEATHER_WIDGET#################");
				Log.i(TAG, "onReceive: action="+intent.getAction());
				Log.i(TAG, "onReceive: weatherArrayList="+intent.getParcelableArrayListExtra("weatherArrayList"));
				Log.i(TAG, "onReceive: action="+intent.getAction());
				ArrayList<Weather_Data>  wd = new ArrayList<Weather_Data>();
				wd = intent.getParcelableArrayListExtra("weatherArrayList");
				Log.i(TAG, "onReceive: wd="+wd.size());
				Log.i("BootCompletedReceiver", "wd.get(0).getWfKor();"+wd.get(0).getWfKor());
				Log.i("BootCompletedReceiver", "wd.get(0).getWfKor();"+wd.get(0).getTemp());
				Log.i("BootCompletedReceiver", "wd.get(1).getWfKor();"+wd.get(1).getWfKor());
				Log.i("BootCompletedReceiver", "wd.get(1).getTemp();"+wd.get(1).getTemp());
				show_data = test_data;
			}			
		}
		//context.startService(new Intent(context, UpdateService.class));
	}
	
	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		
		RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.t_friend_widget);	
 
		final int N = appWidgetIds.length;
		Log.i(TAG, "N ===========>"+ N);
		for (int i=0; i<N; i++) {
	        int appWidgetId = appWidgetIds[i];
	
	        //인텐드와 엑티비티를 연결한다.	            
			Intent intent1 = new Intent(context, Traffic_Info.class);
			Intent intent2 = new Intent(context, Weather_Info.class);
	
			//위젯에서 호출할수 있게...
			PendingIntent pi1 = PendingIntent.getActivity(context, 0, intent1, 0);
			PendingIntent pi2 = PendingIntent.getActivity(context, 0, intent2, 0);
	
			//클릭했을시 이동함...
			updateViews.setOnClickPendingIntent(R.id.img_t_button, pi1);
			updateViews.setOnClickPendingIntent(R.id.img_t_iconbutton, pi2);
		
			appWidgetManager.updateAppWidget(appWidgetId, updateViews);
		}
		
		context.startService(new Intent(context, UpdateService.class));
	} 
	
	public static class UpdateService extends Service implements Runnable {
		
		private Handler mHandler;
		private static final int TIMER_PERIOD = 1 * 1000;

		private long preTime;
		private long curTime;
		
		@Override
		public void onCreate() {			
			mHandler = new Handler();
			Log.i(TAG, "UpdateService : onCreate()");
		}

		@Override
		public void onStart(Intent intent, int startId) {
			Log.i(TAG, "UpdateService : onStart()");
			preTime = System.currentTimeMillis();// - DAY_TIME;			
			mHandler.postDelayed(this, 1000);				
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			Log.i(TAG, "#########run()#########");
			curTime = System.currentTimeMillis();
			
			RemoteViews views = new RemoteViews(this.getPackageName(), R.layout.t_friend_widget);
			
			long CUR_PERIOD = curTime - preTime;
			//if( CUR_PERIOD > 1000 ){WIDGET_ROLLING_TIME
			if( CUR_PERIOD > com.skt.TFriend.util.Constants.WIDGET_ROLLING_TIME ){				
				//views.setTextViewText(R.id.txtView, ""+Integer.toString(curCount));				
				if(category.equals(NEWS)){
					views.setViewVisibility(R.id.lly_new, View.VISIBLE);
					views.setViewVisibility(R.id.txt_message, View.GONE);
					
					int index = random.nextInt(new_title.length);
					
					views.setTextViewText(R.id.txt_new_title,new_title[index]);
					views.setImageViewResource(R.id.img_new_icon, new_image[index]);
					
				}else if(category.equals(WEATHER)){
					views.setViewVisibility(R.id.txt_message, View.VISIBLE);
					views.setViewVisibility(R.id.lly_new, View.GONE);
					
					int index = random.nextInt(weather_data.length);
					
					views.setTextViewText(R.id.txt_message, weather_data[index]);
					
					if(mHandler.postDelayed(this, 300000)){
						Log.i(TAG, "#######true############");
					}else{
						Log.i(TAG, "#######false############");
					}	
				}
				//views.setTextViewText(R.id.txt_message, ""+ show_data[random.nextInt(weather_data.length)]);
				preTime = curTime;
				//curCount++;
			}
			
			//위젯이 업데이트 되었음을 알림.
			AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
			ComponentName testWidge = new ComponentName(this, T_Friend_Widget.class);
			
			appWidgetManager.updateAppWidget(testWidge, views);
			
			if(endServiceFlag){
				Log.i(TAG, "endServiceFlag =>"+endServiceFlag);
				return;
			}else{
				mHandler.postDelayed(this, TIMER_PERIOD);
			}
		}

		@Override
		public IBinder onBind(Intent intent) {
			// TODO Auto-generated method stub
			return null;
		}

	}
//	public static class UpdateService extends IntentService {
//
//		public UpdateService() {
//			super("com.skt.TFriend");
//			
//		}
//
//		@Override
//		protected void onHandleIntent(Intent intent) {
//			// TODO Auto-generated method stub
//			Log.i(TAG, "onHandleIntent : onHandleIntent");
//			ComponentName me=new ComponentName(this, T_Friend_Widget.class);
//			AppWidgetManager mgr = AppWidgetManager.getInstance(this);
//			
//			mgr.updateAppWidget(me, buildUpdate(this));			
//		}
//		
	
//		private RemoteViews buildUpdate(Context context) {
//			Log.i(TAG, "buildUpdate : buildUpdate");
//			RemoteViews updateViews = null;	
//			
//			updateViews = new RemoteViews(context.getPackageName(), R.layout.t_friend_widget);
//			Log.i(TAG, "buildUpdate : buildUpdate"+context.getPackageName());
//			//버튼 클릭시 상세 화면 이동
//			Intent intent1 = new Intent(this, Traffic_Info.class);
//			Intent intent2 = new Intent(this, Weather_Info.class);
//			
//			//위젯에서 호출할수 있게...
//			PendingIntent pi1 = PendingIntent.getActivity(context, 0, intent1, 0);
//			PendingIntent pi2 = PendingIntent.getActivity(context, 0, intent2, 0);
//			
//			//클릭했을시 이동함...
//			updateViews.setOnClickPendingIntent(R.id.liy_1, pi1);
//			updateViews.setOnClickPendingIntent(R.id.liy_2, pi2);
//			
//			return updateViews;			
//		}
//		
//	}	
}
